/* (C) Copyright 2024, ZWSOFT Co., LTD.(Guangzhou) All Rights Reserved. */
/** @file Funciton.cpp
 *  @brief 解析器与评估器
 *  @details 解析，读取源码文件，运行优化后的代码
 */
#include "Function.hpp"
#include <regex>


using namespace std;

Function::Function(const string& func_title) {
	set_func_info(func_title);
};

Function::Function(const vector<string>& code_, const size_t start, const size_t end) {
	m_isDefined = true;
	// 代码为code_中处于start到end的代码段
	m_code = vector<string>(code_.begin() + start, code_.begin() + end);	// 提取代码片段
	const string& code_line = m_code[0];
	set_func_info(code_line);
};

/**
* @brief 主函数运行接口，仅限外部调用
* @return	计算的结果，并转化为字符串
*/
string Function::run(const vector<string>& ps_str, unordered_map<string, Function>& funcs) {
	// 进入此函数，说明执行的是mainFunc函数,对参数列表params进行初始化，然后当作一般函数执行
	size_t lenghtOfVariableToSet = ps_str.size();
	size_t lenghtOfVariableToBeSet = m_inputs.size();
	if (lenghtOfVariableToSet != lenghtOfVariableToBeSet) {
		cout << "Error: sum of parameters didn't match, { " << lenghtOfVariableToSet << "-->" << lenghtOfVariableToBeSet << "} in { mainFunc }, ignore and continue!" << endl;
		lenghtOfVariableToSet = min(lenghtOfVariableToSet, lenghtOfVariableToBeSet);
	}
	// 设置参数列表
	Params ps;
	for (size_t i = 0; i < lenghtOfVariableToSet; ++i) {
		Variable var(m_inputs[i], ps_str[i]);
		ps.add(var);
	}
	Variable resultVariable = function_run(ps);
	if (resultVariable.name == "error") {
		return "error";
	}
	string result = resultVariable.get_value();
	return result;
}

/**
* @brief 传入参数，运行函数
* @return	计算的结果，void类型函数返回默认变量值
*/
Variable Function::function_run(Params& ps) {
	Variable result(m_out);
	// 执行函数体
	size_t i = 1, len = m_code.size();
	while (i < len) {
		string& codeLine = m_code[i];
		bool isConst = false;
		Type type;
		// name_start_id：
		// 0为非变量定义定义，
		// >0数字为函数定义，并且代表首个参数的开始位置（包括前缀）
		// -1无效代码，-2return，-3if，-4else，-5for，-6while
		int nameStartId = set_definition(codeLine, isConst, type);
		// 1.行代码按逗号拆分为块，并存储新定义的变量
		std::vector<std::string> blockList;
		if (nameStartId > 0) {  // 新定义的变量
			// 从name_start_id开始，按照逗号分割，获取每一个变量名，添加到params中，并去掉前缀后拆分成代码块
			line_split(codeLine.substr(nameStartId), true, isConst, type, blockList, ps);
		}
		else if (nameStartId == 0) {		//执行语句
			line_split(codeLine.substr(0), false, isConst, type, blockList, ps);
		}
		else if (nameStartId == -1) {		//无效语句
			i++;
			continue;
		}
		else if (nameStartId == -2) {		//返回语句return
			string returnExpr = codeLine.substr(6);
			returnExpr.pop_back();		// 去掉末尾的分号
			returnExpr.erase(0, returnExpr.find_first_not_of(" "));
			returnExpr.erase(0, returnExpr.find_first_not_of(" "));
			Variable returnResult = evaluate_exp(returnExpr, ps);
			stack<char> rt_pre;
			rt_pre = m_out.ptr_ref;
			int var_new = 0;
			bool set_success = result.set_value(returnResult);
			result.ptr_ref = returnResult.ptr_ref;
			//cout << codeLine << "=>" << result.get_value() << endl;
			if (!set_success) {
				cout << "{" << codeLine << "}" << endl;
				return Variable("error");
			}
			return result;
		}
		// 2.特殊语句

		// 9.块代码按等号拆分为左右
		int variableNew = -1;
		if (nameStartId > 0)
			variableNew = 0;
		else
			variableNew = 1;
		for (auto& singleBlockCode : blockList) {
			if (singleBlockCode.size() < 3) {
				continue;
			}
			string leftText, rightText;
			// 1存在，-1不存在
			int line_state = equal_split(singleBlockCode, leftText, rightText, ps);

			if (line_state == 1) {  //有等号

				isConst;
				type = NONE;		// 解析的语句中的type，如果该变量已定义，typt=NONE
				stack<char> ptr_ref_left;
				string pureName;
				get_str_type_r(leftText, ps, ptr_ref_left, pureName);
				Variable& left = ps.get(pureName);

				Variable blockResult = evaluate_exp(rightText, ps);
				stack<char> ptr_ref_r;
				get_str_type_r(rightText, ps, ptr_ref_r, pureName);
				bool set_success = left.set_value(variableNew, ptr_ref_left, stack<char>(), blockResult);		// 将返回值设定到left内部
				//cout << codeLine << "=>" << left.get_value() << endl;
				if (!set_success) {
					cout << "{" << codeLine << "}" << endl;
					return Variable("error");
				}

			}
			else {  //没有等号
				Variable line_result = evaluate_exp(rightText, ps);
				// 调用函数，且没有返回值
			}
		}
		i++;
	}
	return Variable();
}

/**
* @brief 设置函数参数，并调用该函数
* @details	根据代码内容，解析并设置参数
* @param expr		代码内容，如func(var1,var2);
* @param psInput		代码块之间的运算符
* @return	计算的结果
*/
Variable Function::set_func_parameters(const string& expr, Params& psInput)
{
	vector<string> funcVariableList;			// 传入的参数名(待解析)
	// 1.对函数调用代码段进行分析，匹配并处理每个函数调用
	size_t pos0 = 0;						// 开始位置
	size_t pos1 = expr.find('(');			// 函数名后面的括号
	size_t pos2 = expr.rfind(')');			// 参数列表后面的括号

	string func_name = expr.substr(pos0, pos1 - pos0);
	string params_str = expr.substr(pos1 + 1, pos2 - pos1 - 1);		//参数列表部分的字符串
	if (m_funcs->find(func_name) == m_funcs->end()) {
		cout << "Error: { " << func_name << " } is not defined" << endl;
		return Variable("error");
	}
	Function func = m_funcs->at(func_name);
	//Function& func = funcs[func_name];
	if (!func.m_isDefined) {	  // 函数已申明，但未定义
        cout << "Error: { " << func_name << " } is declared but not defined" << endl;
		return Variable("error");
	}
	// 2.拆分变量部分内容
	string token;
	size_t posStart = 0;
	size_t posCur = 0;
	int bracket_count = 0;
	size_t len = params_str.size();
	while (posCur < len) {
		if (params_str[posCur] == '(') {
			bracket_count++;
			posCur++;
		}
		else if (params_str[posCur] == ')') {
			bracket_count--;
			posCur++;
		}
		else if (params_str[posCur] == ',') {
			if (bracket_count == 0) {
				token = params_str.substr(posStart, posCur - posStart);
				token.erase(std::remove(token.begin(), token.end(), ' '), token.end());
				funcVariableList.emplace_back(token);
				posCur++;
				posStart = posCur;
			}
			else {
				posCur++;
			}
		}
		else {
			posCur++;
		}
	}
	token = params_str.substr(posStart, posCur - posStart);
	token.erase(std::remove(token.begin(), token.end(), ' '), token.end());
	if (!token.empty())
		funcVariableList.emplace_back(token);

	// 3.对参数列表进行赋值
	size_t len_to_set = funcVariableList.size();			// 传递的参数个数（从函数调用语句解析出来的）
	size_t len_to_be_set = func.m_inputs.size();	// 函数定义的参数个数（从函数定义解析出来的）
	if (len_to_set != len_to_be_set) {
		cout << "Error: sum of parameters didn't match, { " << len_to_set << "-->" << len_to_be_set << "} in { " << expr << " }, ignore and continue!" << endl;
		len_to_set = min(len_to_set, len_to_be_set);
	}
	Params parameters;
	for (size_t i = 0; i < len_to_set; ++i) {
		// 2.1解析每个字段的属性
		bool isConst;
		Type type;		// 解析的语句中的type，如果该变量已定义，typt=NONE
		stack<char> ptr_ref_left_pre;
		string pureName;
		//-1未知型，1已定义，2数字，3函数名，4浮点数，5表达式
		//int variableNew = get_str_type(funcVariableList[i], psInput, isConst, type, ptr_ref_left_pre, pureName);
		int var_new = get_str_type_r(funcVariableList[i], psInput, ptr_ref_left_pre, pureName);

		if (var_new == -1) {			// 解析失败
			cout << "Error: { " << funcVariableList[i] << " } is not defined" << endl;
			return Variable();
		}
		else if (var_new == 1) {	// 已定义
			Variable funcVariable = func.m_inputs[i].copy();
			stack<char> funcVarPretext;
			bool setSuccess = funcVariable.set_value(0, funcVarPretext, ptr_ref_left_pre, psInput.get(pureName));
			//cout << expr << "=>" << funcVariable.get_value() << endl;
			if (!setSuccess) {
				cout << "{" << expr << "}" << endl;
				return Variable("error");
			}
			parameters.add(funcVariable);
		}
		else if (var_new == 2 || var_new == 4) {	// 数字
			parameters.add(Variable(func.m_inputs[i], pureName));
		}
		else if (var_new == 3) {	// 函数名
			//cout << "#############waiting to implementation: " << funcVariableList[i] << " is not defined" << endl;
			Variable funcVariable(func.m_inputs[i]);
			Variable result = set_func_parameters(funcVariableList[i], psInput);
			if (result.name == "error") {
				cout << "Error: { " << func_name << " } is not defined" << endl;
				return Variable("error");
			}
			bool set_success = funcVariable.set_value(result);
			if (!set_success) {
				cout << "{" << expr << "}" << endl;
				return Variable("error");
			}
			parameters.add(funcVariable);
		}
		else if (var_new == 5) {
			//cout << "#############waiting to implementation: " << funcVariableList[i] << " is not defined" << endl;
			string expresionStr = funcVariableList[i];
			if (expresionStr[0] == '(')
				expresionStr = expresionStr.substr(1, expresionStr.size() - 2);
			Variable func_var(func.m_inputs[i]);
			Variable var_got = evaluate_exp(expresionStr, psInput);
			bool set_success = func_var.set_value(var_got);
			if (!set_success) {
				cout << "{" << expr << "}" << endl;
				return Variable("error");
			}
			parameters.add(func_var);
		}
	}
	// 4. 运行函数
	Variable result = func.function_run(parameters);
	if (result.name == "error") {
		return result;
	}
	return result;
}

/**
* @brief 表达式计算
* @details	计算字符串表达式的值，如"3 + 5",获得8
* @param varList	代码块列表
* @param ops		代码块之间的运算符
* @return	计算的结果
*/
Variable Function::evaluate_exp(std::string& right_text, Params& ps) {
	string ops;
	vector<string> blockList;
	bool codeBlockGot = experation_split(right_text, blockList, ops);
	if (!codeBlockGot)
		return Variable();
	// 1.优先计算乘除法
	unordered_map<string, Variable> midVariables;
	char midSymble = 'A';
	int i = 0;
	while (i < ops.size()) {
		while (i < ops.size()) {
			if (ops[i] == '*' || ops[i] == '/') {
				break;
			}
			i++;
		}
		if (i >= ops.size()) break;

		Variable variable1 = str_to_var(blockList[i], ps, midVariables);
		Variable variable2 = str_to_var(blockList[i + 1], ps, midVariables);

		Variable midVariable;
		if (ops[i] == '*') {
			midVariable = variable1 * variable2;
		}
		else if (ops[i] == '/') {
			midVariable = variable1 / variable2;
		}
		string midVariableName = "$";
		midVariableName.append(to_string(midSymble));
		midVariables[midVariableName] = midVariable;
		ops.erase(i, 1);
		blockList.erase(blockList.begin() + i);
		blockList[i] = midVariableName;
		midSymble++;
	}

	// 2.然后计算加减法
	Variable result = str_to_var(blockList[0], ps, midVariables);

	size_t len = ops.size();
	for (size_t opsIndex = 0; opsIndex < len; opsIndex++) {
		size_t var_index = opsIndex + 1;
		Variable var1 = str_to_var(blockList[var_index], ps, midVariables);
		if (ops[opsIndex] == '+')
			result = result + var1;
		else if (ops[opsIndex] == '-')
			result = result - var1;
	}
	return result;
}

/**
* @brief 将一行代码，去除const,int之后，按照逗号，拆分成一个个代码块，每句单独执行
* @param blockCode 一行去除const,int之后的代码(输入)
* @param isNew 是否是新定义的变量
* @param blockList 待赋值
* @param ps 如果is_new为true，则需要添加到ps中
* @return bool false拆分失败，true成功
*/
void Function::line_split(const std::string& codeLine, const bool isNew, const bool isConst, const Type type,
	std::vector<std::string>& blockList, Params& ps) {
	// 如果是新定义变量的代码块，则不带前缀添加到block_list，否则带前缀添加添加
	// 按照逗号拆分
	int startId = 0;
	int count = 0;
	if (isNew) {
		for (size_t i = 0; i < codeLine.size(); i++) {
			if (codeLine[startId] == ' ') {
				startId++;;
			}
			if (codeLine[i] == '(') {
				count++;
			}
			else if (codeLine[i] == ')') {
				count--;
			}
			else if (count != 0) {
				continue;
			}
			else if (codeLine[i] == ',') {
				string codeBlock = codeLine.substr(startId, i - startId);  //去除空格
				if (!codeBlock.empty()) {
					stack<char> ptr_ref;
					int pureNameStartId = 0;
					char c = codeBlock[pureNameStartId];
					while (c == '&' || c == '*') {
						ptr_ref.push(c);
						c = codeBlock[++pureNameStartId];
					}
					while (codeBlock[pureNameStartId] == ' ') pureNameStartId++;  // 去除前面空格
					int pure_name_eid = pureNameStartId;
					while (pure_name_eid < codeBlock.size() && codeBlock[pure_name_eid] != '=')
						pure_name_eid++;
					string pure_name = codeBlock.substr(pureNameStartId, pure_name_eid - pureNameStartId);
					pure_name.erase(pure_name.find_last_not_of(" ") + 1);
					Variable new_var(isConst, type, ptr_ref, pure_name);
					string name = ps.add(new_var);
					blockList.emplace_back(codeBlock.substr(pureNameStartId));
				}
				startId = i + 1;
			}
		}
		string code_block = codeLine.substr(startId);
		if (!code_block.empty()) {
			while (code_block.back() == ';')
				code_block.pop_back();
			stack<char> ptr_ref;
			int pureNameStartId = 0;
			char c = code_block[pureNameStartId];
			while (c == '&' || c == '*') {
				ptr_ref.push(c);
				c = code_block[++pureNameStartId];
			}
			while (code_block[pureNameStartId] == ' ') pureNameStartId++;  // 去除前面空格
			int pure_name_eid = pureNameStartId;
			while (pure_name_eid < code_block.size() && code_block[pure_name_eid] != '=')
				pure_name_eid++;
			string pure_name = code_block.substr(pureNameStartId, pure_name_eid - pureNameStartId);
			pure_name.erase(pure_name.find_last_not_of(" ") + 1);
			Variable new_var(isConst, type, ptr_ref, pure_name);
			string name = ps.add(new_var);
			blockList.emplace_back(code_block.substr(pureNameStartId));
		}
	}
	else {
		for (size_t i = 0; i < codeLine.size(); i++) {
			if (codeLine[startId] == ' ') {
				startId++;;
			}
			if (codeLine[i] == '(') {
				count++;
			}
			else if (codeLine[i] == ')') {
				count--;
			}
			else if (count != 0) {
				continue;
			}
			else if (codeLine[i] == ',') {
				string codeBlock = codeLine.substr(startId, i - startId);  //去除空格
				if (!codeBlock.empty()) {
					blockList.emplace_back(codeBlock);
				}
				startId = i + 1;
			}
		}
		string code_block = codeLine.substr(startId);
		if (!code_block.empty()) {
			while (code_block.back() == ';')
				code_block.pop_back();
			blockList.emplace_back(code_block);
		}
	}
}

/**
* @brief 将一个代码块（两个逗号中间的）按照等号拆分成左右两段
* @param blockCode 一个代码块(输入)
* @param left_code 等号左侧(待赋值)
* @param right_code 等号右侧(待赋值)
* @param ps 用于查询
* @return int -1无法分析的属性，1有等号，是赋值语句，2有return关键字，3是定义变量的语句，4if，5for，6while
*/
int Function::equal_split(const std::string blockCode, std::string& leftText, std::string& rightText, Params& ps) {
	leftText.clear(), rightText.clear();
	size_t pos = blockCode.find('=');
	if (pos != string::npos) {			// 等号存在
		leftText = blockCode.substr(0, pos - 1);
		leftText.erase(leftText.find_last_not_of(" ") + 1);	// 去除后面的空格
		rightText = blockCode.substr(pos + 1);
		rightText.erase(0, rightText.find_first_not_of(" "));	// 去除前面的空格
		return 1;
	}
	/*
	else if (blockCode.find("return") != string::npos) {		// 有return关键字
		rightText = blockCode.substr(6, blockCode.size() - 7);	// 去掉末尾分号
		rightText.erase(0, rightText.find_first_not_of(" "));
		return 2;
	}
	else if (blockCode.find("if") != string::npos) {
		return 4;
	}
	else if (blockCode.find("for") != string::npos) {
		return 5;
	}
	else if (blockCode.find("while") != string::npos) {
		return 6;
	}
	*/
	else if (blockCode.size() > 2) {
		rightText = blockCode;
		return 3;
	}

	return -1;

}
/**
* @brief 将等号右侧的表达式拆分成一个个相当于一个变量的小块
* @details 拆分后，每个代码块的形式为：数字、变量、函数调用
* @param expr 等号右侧待拆解的的字符串
* @param varList 代码块容器
* @param ops 运算符，数量比代码块数少1
* @param pureName 纯变量名称
*/
bool Function::experation_split(std::string& expr, vector<string>& varList, string& ops) {
	expr.erase(remove_if(expr.begin(), expr.end(), ::isspace), expr.end());
	if (expr.empty()) return false;
	// 1.提取语句中的每个符号连接的代码段，存入func_expr中
	string delimiter = "+-*/()"; // 分隔符包含 + 和 -
	string token;
	size_t posStart = 0;
	size_t posCur = 0;
	int bracketCount = 0;
	bool in_var = false;
	size_t len = expr.size();
	if (expr[0] == '+' || expr[0] == '-') {
		varList.emplace_back("0");
		ops += expr[0];
		posStart = 1;
		posCur = 1;
	}
	while (posCur < len) {
		if (expr[posCur] == '(') {
			bracketCount++;
			posCur++;
			in_var = true;
		}
		else if (expr[posCur] == ')') {
			bracketCount--;
			posCur++;
		}
		else if (bracketCount != 0) {
			posCur++;
			continue;
		}
		else if (expr[posCur] == '*') {
			if (in_var) {
				token = expr.substr(posStart, posCur - posStart);
				token.erase(remove_if(token.begin(), token.end(), ::isspace), token.end());
				ops += expr[posCur];
				varList.emplace_back(token);
				posCur++;
				posStart = posCur; // 移动到下一个分隔符之后
				in_var = false;
			}
			else {
				posCur++;
			}
		}
		else if (expr[posCur] == '/') {
			token = expr.substr(posStart, posCur - posStart);
			token.erase(remove_if(token.begin(), token.end(), ::isspace), token.end());
			ops += expr[posCur];
			varList.emplace_back(token);
			posCur++;
			posStart = posCur; // 移动到下一个分隔符之后
			posCur = posStart;
			in_var = false;
		}
		else if (expr[posCur] == '+' || expr[posCur] == '-') {
			if (posCur + 1 < len && expr[posCur + 1] == expr[posCur]) {  //++,--
				posCur = posCur + 2;
			}
			else {
				token = expr.substr(posStart, posCur - posStart);
				token.erase(remove_if(token.begin(), token.end(), ::isspace), token.end());
				ops += expr[posCur];
				varList.emplace_back(token);
				posCur++; // 移动到下一个分隔符之后
				posStart = posCur;
				in_var = false;
			}
		}
		else if (expr[posCur] != ' ' && expr[posCur] != '&') {
			in_var = true;
			posCur++;
		}
		else {
			posCur++;
		}
	}
	token = expr.substr(posStart);
	token.erase(remove_if(token.begin(), token.end(), ::isspace), token.end());
	if (!token.empty()) {
		varList.emplace_back(token);
	}

	if (varList.size() != ops.size() + 1) {
		cout << "Error: " << expr << ": " << "ops and var_list didn't match" << endl;
		return false;
	}
	return true;
}


void Function::set_func_info(const string& funcTitle) {
	// 1.获取函数名
	size_t pos0 = 0;						//开始
	size_t pos1 = funcTitle.find('(');		//函数名后面的括号
	size_t pos2 = funcTitle.rfind(')');
	string return_type_str = funcTitle.substr(pos0, pos1 - pos0 + 1);		// 返回值类型字符串
	Params ps;
	bool returnIsConst;	// 占位变量，解析函数名时，返回值忽略const的情况
	Type returnType;
	stack<char> return_ptr_ref;
	//-1未知型，0新定义，1已定义，2数字，3函数名，4浮点数，5表达式
	int var_new = get_str_type(return_type_str, ps, returnIsConst, returnType, return_ptr_ref, m_name);
	m_out = Variable(returnIsConst, returnType, return_ptr_ref, m_name);

	// 2.解析函数参数列表，获取函数重载名
	string varTypeNames = funcTitle.substr(pos1 + 1, pos2 - pos1 - 1);	// 参数列表
	istringstream stream(varTypeNames);
	string variableTypeName;
	while (getline(stream, variableTypeName, ',')) {	// 解析参数列表
		bool variableIsConst;
		Type variableType;
		stack<char> ptr_ref;	// 被push进list后，无用，可pop
		string var_name;
		var_new = get_str_type(variableTypeName, ps, variableIsConst, variableType, ptr_ref, var_name);
		m_inputs.emplace_back(Variable(variableIsConst, variableType, ptr_ref, var_name));

		m_fullName += variableType;

		string ptr_ref_name;
		while (!ptr_ref.empty()) {
			ptr_ref_name += ptr_ref.top();
			ptr_ref.pop();
		}
		ptr_ref_name = string(ptr_ref_name.rbegin(), ptr_ref_name.rend());
		m_fullName.append(ptr_ref_name);
	}
	m_fullName = m_name;
}
/**
* @brief 解析=左侧变量或变量定义的属性
* @details 返回值代表指针层数，绝对值表示指针层数，小于0代表是引用，0代表普通变量
* @param name_pre 待解析的字符串
* @param isConst 是否为const
* @param type 内部数据类型（实际类型）
* @param ptr_num 该变量的指针层数
* @param ref_num 该变量的引用层数
* @param pureName 纯变量名称
* @return result= -1未识别，0新定义，1已定义，24整数和浮点数，3代表字段为函数，5小括号表达式;
*/
int Function::get_str_type(string type_name, Params& ps, bool& is_const, Type& type, stack<char>& ptr_ref, string& pure_name)
{
	if (type_name[0] == '(')
		return 5;
	is_const = false;
	type = NONE;
	if (ptr_ref.size() != 0) return -1;
	pure_name = "";
	int result = -1;
	// 1.搜索引用的数量
	size_t pos0 = 0, pos1 = 0;
	vector<string> splitList;
	for (size_t i = 0; i < type_name.size(); i++) {
		if (type_name[i] == '*') {
			ptr_ref.push('*');
			pos1 = i;
		}
		else if (type_name[i] == '&') {
			ptr_ref.push('&');
			pos1 = i;
		}
		else if (type_name[i] == ' ' || type_name[i] == ';') {
			pos1 = i;
		}
		else if (type_name[i] == '(') {
			pos1 = i;
			type_name = type_name.substr(0, pos1 + 1);
			break;
		}
		else {
			continue;
		}
		if (type_name[pos0] == '*' || type_name[pos0] == '&' || type_name[pos0] == ' ' || type_name[pos0] == ';')
			++pos0;
		if (pos1 > pos0) {
			splitList.emplace_back(type_name.substr(pos0, pos1 - pos0));
			pos0 = pos1 + 1;
		}
	}
	// 处理最后一个部分
	if (pos0 < type_name.size()) {
		splitList.emplace_back(type_name.substr(pos0));
	}
	string& strLast = splitList.back();
	if (strLast.back() == '(')
		if (strLast.size() > 1)
			strLast.pop_back();
		else
			splitList.pop_back();
	pure_name = splitList.back();
	for (int i = 0; i < splitList.size() - 1; ++i) {
		string typeNameStr = splitList[i];
		if (typeNameStr == "const") {
			is_const = true;
		}
		else if (typeNameStr == "int") {
			type = INT;
		}
		else if (typeNameStr == "long") {
			type = LONG;
		}
		else if (typeNameStr == "char") {
			type = CHAR;
		}
		else if (typeNameStr == "double") {
			type = DOUBLE;
		}
		else if (typeNameStr == "bool") {
			type = BOOL;
		}
		else if (typeNameStr == "void") {
			type = VOID;
		}
	}
	if (type != NONE) {		// 没有解析出类型，说明是新定义的变量
		result = 0;		// 0新定义的变量
	}
	else if (ps.exist(pure_name)) {
		type = ps.get(pure_name).get_type();
		result = 1;
	}
	else if (isdigit(pure_name[0]) || (pure_name[0] == '-' && pure_name.size() > 1)) {
		if (pure_name.find('.') == std::string::npos) {
			type = INT;
			result = 2;
		}
		else {
			type = DOUBLE;
			result = 4;
		}
	}
	else if (type_name.back() == '(') {
		result = 3;		//函数名
	}
	return result;
}

int Function::set_definition(std::string& expr, bool& isConst, Type& type) {
	// return:
	// 0为非变量定义定义，
	// >0数字为函数定义，并且代表首个参数的开始位置（包括前缀）
	// -1无效代码，-2return，-3if，-4else，-5for，-6while
	isConst = false;
	type = NONE;
	if (expr.size() < 4) {  // 无效的代码如{}，i++;长度4，int a;长度6（含分号）
		return -1;
	}
	else if (expr.substr(0, 6) == "return") {
		return -2;
	}
	else if (expr.substr(0, 2) == "if") {
		return -3;
	}
	else if (expr.substr(0, 4) == "else") {
		return -4;
	}
	else if (expr.substr(0, 3) == "for") {
		return -5;
	}
	else if (expr.substr(0, 5) == "while") {
		return -6;
	}
	int nameStartId = 0;
	if (expr.substr(0, 5) == "const" && expr[5] == ' ') {
		isConst = true;
		if (expr.substr(6, 3) == "int") {
			type = INT;
			nameStartId = 9;
		}
		else if (expr.substr(6, 4) == "long") {
			type = LONG;
			nameStartId = 10;
		}
		else if (expr.substr(6, 4) == "char") {
			type = CHAR;
			nameStartId = 10;
		}
		else if (expr.substr(6, 6) == "double") {
			type = DOUBLE;
			nameStartId = 12;
		}
		else if (expr.substr(6, 4) == "bool") {
			type = BOOL;
			nameStartId = 10;
		}
		else {
			cout << "error: const must be int,long,char,double,bool" << endl;
		}
	}
	else {
		isConst = false;
		if (expr.substr(0, 3) == "int") {
			type = INT;
			nameStartId = 3;
		}
		else if (expr.substr(0, 4) == "long") {
			type = LONG;
			nameStartId = 4;
		}
		else if (expr.substr(0, 4) == "char") {
			type = CHAR;
			nameStartId = 4;
		}
		else if (expr.substr(0, 6) == "double") {
			type = DOUBLE;
			nameStartId = 6;
		}
		else if (expr.substr(0, 4) == "bool") {
			type = BOOL;
			nameStartId = 4;
		}
	}
	return nameStartId;
}


int Function::get_str_type_r(string name_pre, Params& ps, stack<char>& ptr_ref, string& pure_name) {
	//return result = -1未识别，1已定义，24整数和浮点数，3代表字段为函数，5小括号表达式;
	if (name_pre.empty())
		return -1;
	else if (name_pre[0] == '(')
		return 5;
	if (ptr_ref.size() != 0) return -1;
	pure_name = "";
	int result = -1;
	// 1.搜索引用的数量
	size_t pos = 0;
	vector<string> splitList;
	for (size_t i = 0; i < name_pre.size(); i++) {
		if (name_pre[i] == '*') {
			ptr_ref.push('*');
		}
		else if (name_pre[i] == '&') {
			ptr_ref.push('&');
		}
		else if (name_pre[i] == ' ') {
		}
		else if (name_pre[i] == '(') {
			name_pre = name_pre.substr(0, i + 1);
			break;
		}
		else if (name_pre[i] == '+' || name_pre[i] == '-' || name_pre[i] == '*' || name_pre[i] == '/') {
			result = 5;
			continue;
		}
		if (name_pre[pos] == '*' || name_pre[pos] == '&' || name_pre[pos] == ' ')
			++pos;
	}
	// 处理最后一个部分
	pure_name = name_pre.substr(pos);
	if (pure_name.back() == '(')
		pure_name.pop_back();

	if (ps.exist(pure_name)) {
		result = 1;
	}
	else if (isdigit(pure_name[0]) || (pure_name[0] == '-' && pure_name.size() > 1)) {
		if (pure_name.find('.') == std::string::npos) {
			result = 2;
		}
		else {
			result = 4;
		}
	}
	else if (name_pre.back() == '(') {
		result = 3;		//函数名
	}
	return result;
}


Variable Function::str_to_var(std::string var_info, Params& ps, unordered_map<string, Variable>& mid_vars) {
	Variable variable;
	if (mid_vars.find(var_info) != mid_vars.end()) {
		variable = mid_vars[var_info];
		mid_vars.erase(var_info);
	}
	else {
		stack<char> ptr_ref;
		string pureName;
		//-1未知型，1已定义，2数字，3函数名，4浮点数，5表达式
		int varNew = get_str_type_r(var_info, ps, ptr_ref, pureName);

		if (varNew == -1) {
			cout << "Error: { " << var_info << " } is not defined" << endl;
		}
		else if (varNew == 1) {
			Variable variableGot = ps.get(pureName);	// 此处拷贝一份出来，不用
			bool isReference, isValue;
			int ptr_n = variableGot.get_ptr_n(ptr_ref, isReference, isValue);	// 获取指定变量的指针层数
			stack<char> var_ptr_ref; //字符串对应变量的指针层数
			while (ptr_n-- > 0) {
				var_ptr_ref.push('*');
			}
			variableGot.ptr_ref = var_ptr_ref;
			variable = variableGot;
		}
		else if (varNew == 2 || varNew == 4) {
			variable = Variable(NONE, var_info);
		}
		else if (varNew == 3) {	// 函数调用
			size_t funcNamePos = ptr_ref.size();
			Variable variableGot = set_func_parameters(var_info.substr(funcNamePos), ps);
			if (variableGot.name == "error") {
				return Variable("error");
			}
			bool isReference, isValue;
			int ptr_n = variableGot.get_ptr_n(ptr_ref, isReference, isValue);	// 获取指定变量加前缀之后的指针层数
			stack<char> variable_ptr_ref; //字符串对应变量的指针层数
			while (ptr_n-- > 0) {
				variable_ptr_ref.push('*');
			}
			variableGot.ptr_ref = variable_ptr_ref;
			variable = variableGot;
		}
		else if (varNew == 5) {	//带括号的表达式
			string expresionStr = var_info.substr(1, var_info.size() - 2);
			Variable variableGot = evaluate_exp(expresionStr, ps);
			variable = variableGot;
		}
	}
	return variable;
}

